<script setup lang="ts">
import { saveTask, submitTask } from "@/api/erc/inspectTask";
import { useBeforeRouteLeave } from "@/hooks/useBeforeRouteLeave";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { TAG_CONFIG } from "../config";
import TaskForm from "./TaskForm.vue";
const props = defineProps(["bacicData", "isformTaskDetail"]);
const emits = defineEmits(["backMainPage", "refresh"]);
const isViewOfForm = defineModel("isViewOfForm");
const route = useRoute();
const router = useRouter();
// 执行工单
const taskTormRef = ref<InstanceType<typeof TaskForm>>();
// 验收表单
const checkFormRef = ref();
// 验收人弹窗是否显示
const dialogVisible = ref(false);
// 验收人表单
const approverIdList = ref([]);
// 验收人表单的值
const formValue = ref<{ acceptor?: string; acceptorId?: number }>({});

const {
  isFormDirty,
  formValue: taskFormValue,
  setDefaultValue
} = useBeforeRouteLeave({ message: "内容未保存，确认退出执行工单吗？", defaultValue: {} });
watch(
  () => props.bacicData,
  () => {
    setDefaultValue(props.bacicData);
  },
  {
    once: true
  }
);
// 返回上一级并刷新数据
const backDetailPage = () => {
  if (isFormDirty.value) {
    PxMessageBox.confirm(`内容未保存，确认退出执行工单吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    }).then(async () => {
      handleGoBack();
    });
  } else {
    handleGoBack();
  }
};
// 保存
const handleDraft = async () => {
  taskTormRef.value.formValue.taskStatus = 2; //状态改为执行中
  transformFormToSave();
  await saveTask(taskTormRef.value.formValue);
  handleGoBack();
};
function transformFormToSave() {
  let taskContentItemDTOList = [];
  let maintenanceWorkOrderListDTOList = [];
  let delMaintenanceWorkOrderIdList = [];
  taskTormRef.value.formValue?.checkJobContentList?.forEach(checkJobContentItem => {
    // 巡检内容
    if (checkJobContentItem.checkContentList) {
      checkJobContentItem.checkContentList.forEach(checkContentItem => {
        taskContentItemDTOList = [...taskContentItemDTOList, ...checkContentItem.list];
      });
    }
    taskTormRef.value.formValue.taskContentItemDTOList = taskContentItemDTOList;
    // 维修工单
    if (checkJobContentItem.maintenanceWorkOrderList) {
      if (checkJobContentItem.checked) {
        const time = checkJobContentItem.maintenanceWorkOrderList.time || {};
        const faultImageList = checkJobContentItem.maintenanceWorkOrderList.faultImageList?.map(item => item?.id || item.response?.data?.id);
        // 添加/编辑维修工单
        maintenanceWorkOrderListDTOList = [
          ...maintenanceWorkOrderListDTOList,
          {
            ...checkJobContentItem.maintenanceWorkOrderList,
            planStartTime: time[0],
            planEndTime: time[1],
            executorInfoList: checkJobContentItem.maintenanceWorkOrderList.customExecutorInfoList,
            faultImageList
          }
        ];
      } else {
        // 删除维修工单
        delMaintenanceWorkOrderIdList = [...delMaintenanceWorkOrderIdList, checkJobContentItem.maintenanceWorkOrderList.id];
      }
    }
    taskTormRef.value.formValue.maintenanceWorkOrderListDTOList = maintenanceWorkOrderListDTOList;
    taskTormRef.value.formValue.delMaintenanceWorkOrderIdList = delMaintenanceWorkOrderIdList;
  });
}
// 完成巡检——校验
const handleValidate = () => {
  taskTormRef.value.validated = true;
  // 是否有未填写的巡检内容结果
  const job = taskTormRef.value.formValue.checkJobContentList.find(jobItem => {
    const item = jobItem.checkContentList.find(contentItem => {
      if (contentItem.list) {
        const result = contentItem.list.find(listItem => !listItem.result && listItem.result !== 0);
        // console.log(item, "result");
        return result;
      }
    });
    return item;
  });
  taskTormRef.value.form.validate(async valid => {
    if (valid && !job) {
      // 新增任务
      dialogVisible.value = true;
    } else {
      PxMessage.error("必填内容未填写");
    }
  });
};
// 完成巡检——提交
const handleSubmit = async () => {
  checkFormRef.value.validate(async valid => {
    if (valid) {
      taskTormRef.value.formValue.taskStatus = 6; //状态改为待审核
      transformFormToSave();
      await submitTask({ ...taskTormRef.value.formValue, ...formValue.value });
      handleGoBack();
      dialogVisible.value = false;
      PxMessage.success("提交成功");
    }
  });
};
// 获取下拉框
const querySelect = async () => {
  const arr = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  approverIdList.value = arr.filter(item => {
    return item.userId !== userInfo.userId;
  });
  // approverIdList.value = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
};
// 获取审批人名称
const approverIdChange = val => {
  const arr = approverIdList.value.filter(item => {
    return item.value === val;
  });

  if (arr && arr.length > 0) {
    formValue.value.acceptor = arr[0].label;
    formValue.value.acceptorId = arr[0].value;
  }
};
const handleGoBack = () => {
  if (route.query.page === "form") {
    router.go(-1);
  } else if (props.isformTaskDetail) {
    // 1\从详情页打开，返回详情页
    isViewOfForm.value = false;
    emits("refresh");
  } else {
    // 2、从列表页打开、返回列表页
    emits("backMainPage");
  }
};
onMounted(() => {
  setDefaultValue(props.bacicData);
  querySelect();
});
</script>
<template>
  <div>
    <div class="view-task-detail">
      <div class="view-task-title">
        <px-button type="primary" icon="ArrowLeft" @click="backDetailPage">返回</px-button>
        <div class="text">{{ bacicData.taskName }}</div>
        <div v-show="!!bacicData.taskStatusDesc" class="status">
          <div class="circle" :style="{ backgroundColor: `${TAG_CONFIG[bacicData.taskStatus]?.color}` }" />
          <p :style="{ color: `${TAG_CONFIG[bacicData?.taskStatus]?.color}` }">{{ bacicData.taskStatusDesc }}</p>
          <p v-if="bacicData.timeOut === 1" :style="{ color: '#EF4444', marginLeft: '4px' }">超期</p>
        </div>
      </div>
    </div>
    <TaskForm v-model="taskFormValue" v-bind="$attrs" ref="taskTormRef" :data="bacicData" />
    <div class="info-form-btns">
      <px-button @click="backDetailPage">取消</px-button>
      <px-button type="primary" ghost @click="handleDraft">保存进度</px-button>
      <px-button type="primary" @click="handleValidate">完成巡检</px-button>
    </div>
    <px-dialog v-model="dialogVisible" title="完成确认" width="60%" align-center>
      <px-form ref="checkFormRef" :inline="false" :model="formValue" label-position="right" label-width="150px">
        <px-form-item class="mb-[0px]" label="验收人" prop="acceptorId" :rules="[{ required: true, message: '验收人不能为空', trigger: 'change' }]">
          <px-select-v2
            v-model="formValue.acceptorId"
            filterable
            clearable
            :options="approverIdList"
            placeholder="请选择出库审批人"
            @change="approverIdChange"
        /></px-form-item>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="dialogVisible = false">取消</px-button>
          <px-button type="primary" @click="handleSubmit">确认提交验收</px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>
<style lang="scss" scoped>
:deep(.px-dialog__footer) {
  padding: 0 24px;
  padding-top: 16px;
}
.info-form-btns {
  position: absolute;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 68px;
  padding-right: 24px;
  background: #fff;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}
.view-task-detail {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;
  .view-task-title {
    display: flex;
    flex-direction: row;
    align-items: center;

    .text {
      margin-left: 20px;
      font-size: 20px;
      font-weight: 600;
      color: rgb(0 0 0 / 90%);
    }

    .status {
      display: flex;
      flex-direction: row;
      align-items: center;

      .circle {
        width: 8px;
        height: 8px;
        margin-left: 8px;
        margin-right: 5px;
        border-radius: 50%;
      }
    }
  }
}
</style>
